/*
 *  Copyright (c) 2013 The CCP project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a Beijing Speedtong Information Technology Co.,Ltd license
 *  that can be found in the LICENSE file in the root of the web site.
 *
 *   http://www.cloopen.com
 *
 *  An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */
package com.yuntongxun.ecdemo.ui.chatting.model;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;

import com.squareup.picasso.Picasso;
import com.yuntongxun.ecdemo.R;
import com.yuntongxun.ecdemo.common.utils.LogUtil;
import com.yuntongxun.ecdemo.storage.ContactSqlManager;
import com.yuntongxun.ecdemo.ui.chatting.ChattingActivity;
import com.yuntongxun.ecdemo.ui.chatting.holder.BaseHolder;
import com.yuntongxun.ecdemo.ui.chatting.holder.DescriptionViewHolder;
import com.yuntongxun.ecdemo.ui.chatting.view.CCPChattingFooter2;
import com.yuntongxun.ecdemo.ui.chatting.view.ChattingItemContainer;
import com.yuntongxun.ecdemo.ui.contact.ECContacts;
import com.yuntongxun.ecdemo.voicechat.bean.PostResult;
import com.yuntongxun.ecdemo.voicechat.bean.UserInfo;
import com.yuntongxun.ecdemo.voicechat.comman.EventBusTags;
import com.yuntongxun.ecdemo.voicechat.comman.GiftContacts;
import com.yuntongxun.ecdemo.voicechat.comman.TopicContacts;
import com.yuntongxun.ecdemo.voicechat.view.MyImageSpan;
import com.yuntongxun.ecsdk.ECMessage;
import com.yuntongxun.ecsdk.im.ECTextMessageBody;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;

import de.greenrobot.event.EventBus;


/**
 * @author Jorstin Chan
 * @date 2014-4-17
 * @version 1.0
 */
public class DescriptionTxRow extends BaseChattingRow{



	public DescriptionTxRow(int type){
		super(type);
	}
	
	/* (non-Javadoc)
	 * @see com.hisun.cas.model.im.ChattingRow#buildChatView(android.view.LayoutInflater, android.view.View)
	 */
	@Override
	public View buildChatView(LayoutInflater inflater, View convertView) {
        //we have a don't have a converView so we'll have to create a new one
        if (convertView == null || ((BaseHolder)convertView.getTag()).getType() != mRowType) {

        	convertView = new ChattingItemContainer(inflater, R.layout.chatting_item_to);

            //use the view holder pattern to save of already looked up subviews
        	DescriptionViewHolder holder = new DescriptionViewHolder(mRowType);
        	convertView.setTag(holder.initBaseHolder(convertView, false));
        }
		return convertView;
	}

	@Override
	public void buildChattingData(Context context, BaseHolder baseHolder,
			ECMessage msg, int position) {
		DescriptionViewHolder holder = (DescriptionViewHolder) baseHolder;
		if (msg != null) {
			String msgType = "";
			JSONArray jsonArray = null;
			if (!TextUtils.isEmpty(msg.getUserData())) try {
				JSONObject jsonObject = new JSONObject(msg.getUserData());
				msgType = jsonObject.getString(CCPChattingFooter2.TXT_MSGTYPE);
				jsonArray = jsonObject.getJSONArray(CCPChattingFooter2.MSG_DATA);

			} catch (JSONException e) {
				e.printStackTrace();
			}



			if (TextUtils.equals(msgType, CCPChattingFooter2.FACETYPE)) {
				holder.getDescTextView().setBackgroundResource(0);
			} else {
				holder.getDescTextView().setBackgroundResource(R.drawable.chat_to_bg_normal);
			}
			ECTextMessageBody textBody = (ECTextMessageBody) msg.getBody();
			String msgTextString = textBody.getMessage();
			if (msgTextString.startsWith("[gift]")){
				holder.getBaseLayout().setVisibility(View.VISIBLE);
				holder.getClickAreaView().setVisibility(View.VISIBLE);
				holder.getDescTextView().setVisibility(View.GONE);
				holder.getTopicLayout().setVisibility(View.GONE);
				holder.getUploadProgressBar().setVisibility(View.GONE);
				holder.getChattingState().setVisibility(View.GONE);
				holder.getReadTv().setVisibility(View.GONE);

				View.OnClickListener onClickListener = ((ChattingActivity) context).mChattingFragment.getChattingAdapter().getOnClickListener();
				ViewHolderTag holderTag = ViewHolderTag.createTag(msg,
						ViewHolderTag.TagType.TAG_GIFT, position);
				holder.getClickAreaView().setTag(holderTag);
				holder.getClickAreaView().setOnClickListener(onClickListener);

			}else if(msgTextString.startsWith("[conf]")) {
				String confInfo = msg.getUserData();
				Log.e("confInfoTx",confInfo);
				holder.getBaseLayout().setVisibility(View.VISIBLE);
				holder.getTopicLayout().setVisibility(View.GONE);
				holder.getUploadProgressBar().setVisibility(View.GONE);
				holder.getChattingState().setVisibility(View.GONE);
				holder.getReadTv().setVisibility(View.GONE);
				String meetingNo="";
				try {
					JSONObject object = new JSONObject(confInfo);
					meetingNo=object.getString("confId");
					PostResult postResult = new PostResult();
					postResult.setTag(EventBusTags.MEETING_NO);
					postResult.setResult(meetingNo+"");
					EventBus.getDefault().post(postResult);

				}catch (Exception e){
					LogUtil.e("roomNo",e.toString());
				}

				if (!TextUtils.isEmpty(meetingNo)){
					holder.getDescTextView().setText("Start a group chat");
				}else{
					holder.getDescTextView().setText("Exit group chat");
				}

				holder.getClickAreaView().setVisibility(View.GONE);
				holder.getDescTextView().setVisibility(View.VISIBLE);
//				holder.getDescTextView().setText(msgTextString);
			}else if((msgTextString.startsWith("[topic]"))) {
				holder.getBaseLayout().setVisibility(View.VISIBLE);
				holder.getClickAreaView().setVisibility(View.GONE);
				holder.getTopicLayout().setVisibility(View.VISIBLE);
				holder.getDescTextView().setVisibility(View.GONE);
				holder.getUploadProgressBar().setVisibility(View.GONE);
				holder.getChattingState().setVisibility(View.GONE);
				holder.getReadTv().setVisibility(View.GONE);
				String question="",answer="";
				int type=0; //0=文本、1=语音
				String topicInfo= msg.getUserData();
				Log.e("---",topicInfo);
				try {
					JSONObject object=new JSONObject(topicInfo);
					question=object.optString("question");
					answer=object.optString("answer");

					type=object.getInt("type");
					if (type==1){
						holder.getQuestionTv().setVisibility(View.GONE);
						holder.getAnswerTv().setVisibility(View.GONE);
						holder.getQuestionBtn().setVisibility(View.VISIBLE);
//						holder.getAnswerBtn().setVisibility(View.VISIBLE);
						Log.e("answer",answer);
						if (answer.toString().trim().equals("")){
							holder.getAnswerBtn().setVisibility(View.INVISIBLE);
						}else{
							holder.getAnswerBtn().setVisibility(View.VISIBLE);
						}
					}else{
						holder.getQuestionTv().setVisibility(View.VISIBLE);
						holder.getQuestionTv().setText(question);
						holder.getAnswerTv().setVisibility(View.VISIBLE);
						holder.getAnswerTv().setText(answer);
						holder.getQuestionBtn().setVisibility(View.GONE);
						holder.getAnswerBtn().setVisibility(View.GONE);
					}
					View.OnClickListener onClickListener = ((ChattingActivity) context).mChattingFragment.getChattingAdapter().getOnClickListener();
					ViewHolderTag holderTag = ViewHolderTag.createTag(msg,
							ViewHolderTag.TagType.TAG_TOPIC_QUESTION, position);
					holder.getQuestionBtn().setTag(holderTag);
					holder.getQuestionBtn().setOnClickListener(onClickListener);

					ViewHolderTag holderTag1 = ViewHolderTag.createTag(msg,
							ViewHolderTag.TagType.TAG_TOPIC_ANSWER, position);
					holder.getAnswerBtn().setTag(holderTag1);
					holder.getAnswerBtn().setOnClickListener(onClickListener);

					ECContacts contact = ContactSqlManager.getContact(msg.getForm());
					String info=contact.getNickname();
//					MyImageSpan nativeSpan = new MyImageSpan(mContext, R.drawable.ic_speak);
//					MyImageSpan learnSpan = new MyImageSpan(mContext, R.drawable.ic_learn);
					if (info.contains("(")) {
						int index = info.indexOf("(");
						String infomation=info.substring(index+1,info.length()-1);
//                    String[] infos=infomation.split("-");
						UserInfo infos=null;
						try {
							infos=parseResult(infomation);
						} catch (Exception e) {
							e.printStackTrace();
						}

						if (infos!=null){
//							holder.infoTv.setText(infos.getNickName());
							String name = infos.getNickName()+"  ";
							String age = "  "+infos.getAge()+"  ";
							String nativel = " ";
							String learn = " ";
							if (infos.getNativeLanguage()!=null){
								nativel="  "+infos.getNativeLanguage()+"  ";
							}
							if (infos.getLearningLanguage()!=null){
								learn="  "+infos.getLearningLanguage()+"";
							}
//
//
							if (infos.getGender().equals("男")){
								genderSpan = new MyImageSpan(mContext, R.drawable.ic_man);
							}else{
								genderSpan = new MyImageSpan(mContext, R.drawable.ic_woman);
							}

//							nativeSpan = new MyImageSpan(mContext, R.drawable.ic_speak);
//							learnSpan = new MyImageSpan(mContext, R.drawable.ic_learn);

							try {
								InputStream is = mContext.getAssets().open("flag/"+infos.getCountry()+".png");
								flagSpan = new MyImageSpan(mContext, BitmapFactory.decodeStream(is));
								is.close();
							} catch (IOException e) {
								Log.e("----",e.toString());
							}

							holder.infoTv.setText("");
							//姓名
							SpannableString nameShow = new SpannableString(name);
							ForegroundColorSpan blackSpan = new ForegroundColorSpan(Color.BLACK);
							nameShow.setSpan(blackSpan,0,name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
							holder.infoTv.append(nameShow);

							//插入性别图标
							SpannableString showString = new SpannableString("1");
							showString.setSpan(genderSpan,0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
							holder.infoTv.append(showString);

							//年龄颜色
							SpannableString ageShow = new SpannableString(age);
							ForegroundColorSpan yellowSpan = new ForegroundColorSpan(mContext.getResources().getColor(R.color.voice_yellow));
							ageShow.setSpan(yellowSpan,0,age.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
							holder.infoTv.append(ageShow);

							//插入国旗图标
							showString.setSpan(flagSpan, 0, 1 , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
							holder.infoTv.append(showString);

							holder.infoTv.append("  ");

//							//插入本地语言的图标
//							showString.setSpan(nativeSpan, 0, 1 , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//							holder.infoTv.append(showString);
//
//							//本地语言颜色
//							SpannableString nativeShow = new SpannableString(nativel);
//							ForegroundColorSpan greenSpan = new ForegroundColorSpan(mContext.getResources().getColor(R.color.voice_green));
//							nativeShow.setSpan(greenSpan,0,nativel.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//							holder.infoTv.append(nativeShow);
//
//							//插入学习的图标
//							showString.setSpan(learnSpan, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//							holder.infoTv.append(showString);
//
//							//学习语言颜色
//							SpannableString learnShow = new SpannableString(learn);
//							ForegroundColorSpan greenSpan1 = new ForegroundColorSpan(mContext.getResources().getColor(R.color.voice_green));
//							learnShow.setSpan(greenSpan1,0,learn.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//							holder.infoTv.append(learnShow);

						}
					}else {
						holder.getBaseLayout().setVisibility(View.VISIBLE);
						holder.getNameTv().setText(msg.getForm());
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}


			}else{
				holder.getBaseLayout().setVisibility(View.VISIBLE);
				holder.getClickAreaView().setVisibility(View.GONE);
				holder.getTopicLayout().setVisibility(View.GONE);
				holder.getDescTextView().setVisibility(View.VISIBLE);
				holder.getUploadProgressBar().setVisibility(View.VISIBLE);
				holder.getChattingState().setVisibility(View.VISIBLE);
				holder.getReadTv().setVisibility(View.VISIBLE);
				holder.getDescTextView().showMessage(msg.getId() + "", msgTextString, msgType, jsonArray);
				holder.getDescTextView().setMovementMethod(LinkMovementMethod.getInstance());
				View.OnClickListener onClickListener = ((ChattingActivity) context).mChattingFragment.getChattingAdapter().getOnClickListener();
				ViewHolderTag holderTag = ViewHolderTag.createTag(msg,
						ViewHolderTag.TagType.TAG_IM_TEXT, position);
				holder.getDescTextView().setTag(holderTag);
				holder.getDescTextView().setOnClickListener(onClickListener);
				setAutoLinkForTextView(holder.getDescTextView());
				getMsgStateResId(position, holder, msg, onClickListener);
			}


		}
	}



	@Override
	public int getChatViewType() {
		return ChattingRowType.DESCRIPTION_ROW_TRANSMIT.ordinal();
	}
	
	@Override
	public boolean onCreateRowContextMenu(ContextMenu contextMenu,
			View targetView, ECMessage detail) {
		
		return false;
	}
	

}
